package com.zzyl.framework.interceptor;

import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 小程序端拦截器
 * @author 16701
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 前置处理，在小程序所有请求过来时，验证token是否有效
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果本次请求的目标资源不是Controller里的方法，则直接放行，不需要处理
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String token = request.getHeader("authorization");
        //如果token为null返回401
        if(token==null || token.isEmpty()){
            response.setStatus(401);
            return false;
        }
        //如果token无效，返回401
        Claims claims = null;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        Long userId = claims.get("id",Long.class);
        //验证成功绑定到线程上，返回true放行
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
